Page({
  data: {
    index: 0,
    show: true,
    recommend_books: {},
    popular_books: [],
    search_results: [],
    isSearching: false,
    searchQuery: '',
    currentPopularPage: 1, // 当前热门书籍的页码
    pageSize: 10, // 每页加载的书籍数量
  },

  async onLoad() {
    wx.showLoading({
      title: '加载中...',
    });

    try {
      const app = getApp();
      const recommendBooks = await app.fetchData(
        'http://1.94.51.11:8849/qualitypush'
      );

      this.setData({ recommend_books: recommendBooks });

      // 加载初始热门书籍数据
      await this.loadMorePopularBooks();
    } catch (error) {
      console.error('Failed to fetch books', error);
    } finally {
      wx.hideLoading();
    }
  },

  async loadMorePopularBooks() {
    const { currentPopularPage, pageSize } = this.data;

    wx.showLoading({
      title: '加载中...',
    });

    try {
      const app = getApp();
      const popularBooks = await app.fetchData(
        'http://1.94.51.11:8849/hotpush',
        { currentPage: currentPopularPage, pageSize }
      );

      // 将新数据与现有数据合并
      this.setData({
        popular_books: [...this.data.popular_books, ...popularBooks],
        currentPopularPage: currentPopularPage + 1, // 更新当前页码
      });
    } catch (error) {
      console.error('Failed to fetch popular books', error);
    } finally {
      wx.hideLoading();
    }
  },

  onReachBottom() {
    // 加载更多热门书籍数据
    this.loadMorePopularBooks();
  },

  onSlideChange(e) {
    this.setData({
      show: false,
    });
    setTimeout(() => {
      this.setData({
        index: e.detail.current,
        show: true,
      });
    }, 300);
  },

  goToDetail(e) {
    const bookId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${bookId}`,
    });
  },

  onInput(e) {
    this.setData({
      searchQuery: e.detail.value,
    });
  },

  async onSearch() {
    const wd = this.data.searchQuery;
    if (!wd) return;

    wx.showLoading({
      title: '搜索中...',
    });

    try {
      const app = getApp();
      const searchResults = await app.fetchData(
        'http://1.94.51.11:8849/searchwork',
        { wd }
      );
      if (!searchResults || searchResults.length === 0) {
        wx.showToast({
          title: '查无此书',
          icon: 'none',
        });
      }
      this.setData({
        search_results: searchResults,
        isSearching: true,
      });
    } catch (error) {
      console.error('Failed to fetch search results', error);
    } finally {
      wx.hideLoading();
    }
  },

  cancelSearch() {
    this.setData({
      isSearching: false,
      searchQuery: '',
    });
  },
});
